#coding=utf8
from model import *
import google.appengine.ext.db as db
import twitter
from twitter import *
import common
import google.appengine.api.users as users
import re
API_SOURCE = '<a href="http://twittertalk.appspot.com">TwitterTalk</a>'

def _getBindingEntry(user,insert=False):
	if user is None:
		return None
	if isinstance(user,(str,unicode)):
		user = users.User(user)
	if insert:
		return BindingModel.get_or_insert(user.email(),user=user)
	else:
		return BindingModel.get_by_key_name(user.email())

getBindingEntry = _getBindingEntry

def isBinding(user = None):
	if user is None:
		user = users.get_current_user()
	if user is None:
		return None
	return _getBindingEntry(user)

def verityTwitterAccount(username,password):
	if not username or not password:
		return None
	api = createApi(username,password)
	return api.VerifyCredentials()

def bindTwitterAccount(user,username,password):
	entry = _getBindingEntry(user,True)
	entry.twitter_username = username
	entry.twitter_password = password
	entry.put()

def unbindTwitterAccount(user):
	entry = _getBindingEntry(user)
	if entry:entry.delete()

def createApi(username=None,password=None,user=None):
	apihost = twitter.DEFAULT_API_HOST if not common.isdevelopment else twitter.PROXY_API_HOST
	#apihost = twitter.PROXY_API_HOST
	api = None
	if username is not None and password is not None:
		api = twitter.Api(username,password,apihost=apihost)
	else:
		if user == None:
			user = users.get_current_user()
		if user:
			entry = _getBindingEntry(user)
			if entry:
				api = twitter.Api(entry.twitter_username,entry.twitter_password,apihost=apihost)
	if api == None:
		return None
	#api.SetSource(API_SOURCE)
	return api